﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Budget.CategoryWCFProxy;
using Newtonsoft.Json;
using Budget.HelperClasses;

namespace Budget.Data
{
	public partial class Categories : System.Web.UI.Page
	{
		private Category cat;

		protected void Page_Load( object sender, EventArgs e )
		{
			string action = Request.Form["xaction"];
			if ( !string.IsNullOrEmpty( action ) )
			{
				switch ( action )
				{
					case "create":
						CreatCategory();
						break;
					case "update":
						UpdateCategory();
						break;
					case "destroy":
						DeleteCategory();
						break;
					default:
						ListCategory();
						break;
				}
			}
		}

		private void CreatCategory()
		{
			Category newCategory = JsonConvert.DeserializeObject<Category>( Request.Form["data"] );
			newCategory.Timestamp = DateTime.Now;

			JsonResponse<Category> response = new JsonResponse<Category>();

			try
			{
				WCFHelper.Using<CategoryServiceClient>( svc => svc.Save( newCategory ) );

				response.Success = true;
				response.Message = "Successfully created Category object.";
			}
			catch ( Exception ex )
			{
				response.Success = false;
				response.Message = "An error occurred while creating Category object.";
			}

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}

		private void UpdateCategory()
		{
			Category updatedCategoryDetails = JsonConvert.DeserializeObject<Category>( Request.Form["data"] );

			JsonResponse<Category> response = new JsonResponse<Category>();

			try
			{
				Category cat = null;
				WCFHelper.Using<CategoryServiceClient>( svc => svc.GetCategoryById( updatedCategoryDetails.CategoryId ) );

				cat.CategoryName = updatedCategoryDetails.CategoryName;
				cat.BudgetAmount = updatedCategoryDetails.BudgetAmount;
				cat.IsActive = updatedCategoryDetails.IsActive;
				cat.Timestamp = DateTime.Now;

				WCFHelper.Using<CategoryServiceClient>( svc => svc.Save( cat ) );

				response.Success = true;
				response.Message = "Successfully created Category object.";
			}
			catch ( Exception ex )
			{
				response.Success = false;
				response.Message = "An error occurred while creating Category object.";
			}

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}

		private void DeleteCategory()
		{
			throw new NotImplementedException();
		}

		private void ListCategory()
		{
			JsonResponse<Category> response = new JsonResponse<Category>();

			WCFHelper.Using<CategoryServiceClient>( svc => response.Data = svc.GetAll() );

			response.Count = response.Data.Count();
			response.Success = true;
			response.Message = "Successfully retrieved all Category objects.";

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}
	}
}
